<template>
    <div class="resourceDialog">

        <el-dialog
            class="resourceForm"
            :title="common.titleTips"
            :visible.sync="common.addResourceTab"
            :before-close="handleClose"
            :close-on-click-modal='false'>
            <el-form :model="resourceCon" :rules="newResRules" ref="resourceCon" label-width="100px" class="demo-ruleForm">
                <el-form-item v-if="common.type=='HDFS'&&!common.isDisabled" label="目录名" prop="url">
                    <el-input maxlength="12" v-model="resourceCon.url" :disabled="common.isDisabled" placeholder="请输入目录名"></el-input>
                </el-form-item>
                <el-form-item v-if="common.type=='HDFS'&&common.isDisabled" label="目录名">
                    <el-input v-model="resourceCon.url" :disabled="common.isDisabled" placeholder="请输入目录名"></el-input>
                </el-form-item>
                <el-form-item class="capUnit" v-if="common.type=='HDFS'" label="容量配额" prop="capacity">
                    <el-tooltip class="item" effect='dark' :content='remainTips' placement="top">
                        <el-input v-model.number="resourceCon.capacity" placeholder="请输入配额"></el-input>
                    </el-tooltip>
                    <el-select v-model="unit" placeholder="请选择" @change="getRemainTest('CHANGE')">
                        <el-option
                            v-for="item in resUnit"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="common.type=='HDFS'" label="文件配额" prop="fileNum">
                    <el-tooltip class="item" effect='dark' :content='remainFileTips' placement="top">
                        <el-input v-model.number="resourceCon.fileNum" placeholder="请输入文件数"></el-input> 个
                    </el-tooltip>
                </el-form-item>
                
                <el-form-item v-if="common.type=='HBASE'" label="命名空间" prop='spaceName'>
                    <el-input maxlength="12" v-model="resourceCon.spaceName" :disabled="common.isDisabled" placeholder="请输入命名空间"></el-input>
                </el-form-item>

                <el-form-item v-if="common.type=='HIVE'" label="库名" prop="databaseName">
                    <el-input maxlength="12" v-model="resourceCon.databaseName" :disabled="common.isDisabled" placeholder="请输入库名"></el-input>
                </el-form-item>

                <el-form-item v-if="common.type=='KAFKA'" label="主题名" prop="topicName">
                    <el-input maxlength="32" v-model="resourceCon.topicName" :disabled="common.isDisabled" placeholder="请输入主题名"></el-input>
                </el-form-item>
                <el-form-item v-if="common.type=='KAFKA'" label="分区数" prop="partitionNum">
                    <el-input v-model.number="resourceCon.partitionNum" :disabled="common.isDisabled" placeholder="请入输分区数"></el-input>
                </el-form-item>
                <el-form-item v-if="common.type=='KAFKA'" label="副本数" prop="replication">
                    <el-tooltip class="item" effect='dark' :content='MaxReplicationNum' placement="top">
                        <el-input v-model.number="resourceCon.replication" :disabled="common.isDisabled" placeholder="请输入副本数"></el-input>
                    </el-tooltip>
                </el-form-item>


            </el-form>
            <span slot='footer' class="dialog-footer">
                <el-button @click="cancelBtn('resourceCon')">取消</el-button>
                <el-button :loading="btnDisabled" type="primary" @click="submitResourceCon('resourceCon')">确认</el-button>
            </span>
        </el-dialog>

        <el-dialog
            class="resourceForm"
            :title="common.operatorTips"
            :visible.sync="common.resOperate"
            :close-on-click-modal='false'>
            <el-form label-width="100px" class="demo-ruleForm">
                <span v-if="common.opeBtn == '1'">
                    <el-form-item :label="common.label" prop="name">
                        <el-input v-model="resourceCon.url" placeholder="请输入" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item v-if="role==2" label="用户" prop="name">
                        <el-select
                            v-model="resourceCon.userList"
                            multiple
                            filterable
                            remote
                            reserve-keyword
                            placeholder="请输入用户名"
                            :remote-method="getUser"
                            :loading="loading">
                            <el-option
                                v-for="item in allUserList"
                                :key="item.userId"
                                :label="item.username"
                                :value="item.username">
                            </el-option>
                        </el-select>
                        支持多选
                    </el-form-item>
                    <el-form-item v-if="role==1" label="租户" prop="name">
                        <el-select
                            v-model="resourceCon.tenantList"
                            multiple
                            filterable
                            remote
                            reserve-keyword
                            placeholder="请输入租户名"
                            :remote-method="getTenant"
                            :loading="loading">
                            <el-option
                                v-for="item in tenantList"
                                :key="item.userId"
                                :label="item.username"
                                :value="item.username">
                            </el-option>
                        </el-select>
                        支持多选
                    </el-form-item>
                </span>
                <span v-if="common.opeBtn == '4'">
                    <span v-if="common.type=='HDFS'">
                        <el-form-item label="资源名称">
                            {{common.editData.name}}
                        </el-form-item>
                        <el-form-item label="容量配额">
                            <span>{{common.editData.capacity}} {{common.editData.unit==1?'MB':common.editData.unit==2?"GB":common.editData.unit==3?'TB':''}}</span>
                        </el-form-item>
                        <el-form-item label="文件配额">
                            {{common.editData.fileNum}}
                        </el-form-item>
                        <el-form-item v-if="common.resTypeName == 'public'" label="分配的租户">
                            <span v-for="(item,index) in common.editData.tenantList" :key="index">
                                {{item}}
                                <span v-if="index!=common.editData.tenantList.length-1">,</span>
                            </span>
                        </el-form-item>
                    </span>
                    <span v-if="common.type=='HBASE'||common.type=='HIVE'">
                        <el-form-item label="资源名称">
                            {{common.editData.name}}
                        </el-form-item>
                        <el-form-item label="分配的用户">
                            <span v-for="(item,index) in common.editData.userList" :key="index">
                                {{item}}
                                <span v-if="index!=common.editData.userList.length-1">,</span>
                            </span>
                        </el-form-item>
                    </span>
                </span>
                <span v-if="common.opeBtn == '3'&&common.type!='YARN'&&common.type!='KAFKA'">
                    <el-form-item label="是否保留数据" prop="name">
                        <el-switch v-model="idDelete" active-text="是" inactive-text="否"></el-switch>
                    </el-form-item>
                </span>
            </el-form>
            <span slot='footer' class="dialog-footer" v-if="common.opeBtn != '4'">
                <el-button @click="cancelBtn">取消</el-button>
                <el-button :loading="btnDisabled" type="primary" @click="submitTenant">确认</el-button>
            </span>
        </el-dialog>

        <el-dialog
            class="resourceForm YARNForm"
            :title='common.YARNtitle'
            :visible.sync="common.editYARN"
            :close-on-click-modal='false'>
            <el-table :data="resourcePublic" stripe style="width: 100%" height="400">
                <el-table-column :label="YARNtableHead[clickStep-1].first">
                    <template slot-scope="scope">
                        <span>{{scope.row.queueName}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="队列占比(%)" width="450">
                    <template class="ratioOperator" slot-scope="scope">
                        <el-button class="countBtn" @click='changCount(0,scope.row.ratio,scope.$index)'>
                            <i class="el-icon-arrow-left"></i>
                        </el-button>
                        <el-slider @change='slideChange' class="slider" v-model="scope.row.ratio"></el-slider>
                        <span class="sliderSpan">{{scope.row.ratio}}</span>
                        <el-button class="countBtn" @click='changCount(1,scope.row.ratio,scope.$index)'>
                            <i class="el-icon-arrow-right"></i>
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <span slot='footer' class="dialog-footer">
                <span class="total">队列占比总计：{{total}} %</span>
                <el-button @click="cancelBtn">取消</el-button>
                <el-button :loading="btnDisabled" type="primary" @click="yarnEdit">确认</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { resUnit, MANAGER_ROLE_CODE, TENANT_ROLE_CODE } from '@/const'
import { parseValueByUnit, getCapacityUnit } from '@/utils'
import { mapState } from "vuex";
import { managerApi } from '@/request'
import { Message } from 'element-ui'
import resource from '@/mixins/resource'
    export default {
        props:['diaData'],
        mixins:[resource],
        data() {
            //url 自定义校验规则
            var validateUrl = (rule, value, callback) => {
                var reg = /(?!^(\d+)$)(?!^(_+)$)^[A-Za-z0-9_]{4,32}$/;
                if(!value){
                    return callback(new Error('请输入内容'));
                }
                if(value === ''){
                    callback(new Error('输入不能为空'));
                } else {
                    if(!this.common.isDisabled){//编辑的时候不校验
                        if(!reg.test(value)){
                            callback(new Error("只能输入长度不小于4位的数字、字母和'_',并且不全为数字或'_'"));
                        }
                    }
                    callback();
                }
            }
            const validateFileNum = (rule, value, callback) => {
                let maxNum = this.unUsedFileNum + this.savedFileNum
                if (value === undefined || value === null || value === '') {
                    callback(new Error('请输入文件配额(格式为数字)'))
                } else if (value > maxNum){
                    callback(new Error('已超出文件最大配额'))
                } else {
                    callback();
                }
            }
            const validateCapacity = (rule, value, callback) => {
                let maxValue
                if (this.savedCapacity.value) {
                    // 当前单位下，已分配的容量
                    let savedUnit = getCapacityUnit(this.savedCapacity.unit)
                    let curUnit = getCapacityUnit(this.unit)
                    let savedValueByCurUnit = parseValueByUnit(this.savedCapacity.value, savedUnit, curUnit)
                    // 最大配额
                    maxValue = this.remainSpace[this.unit] + savedValueByCurUnit
                } else {
                    // 新建资源
                    maxValue = this.remainSpace[this.unit]
                }
                
                if (value === undefined || value === null || value === '') {
                    callback(new Error('请输入配额(格式为数字)'))
                } else if (value > maxValue){
                    callback(new Error('已超出可分配容量的最大配额'))
                } else {
                    callback();
                }
            }
            return {
                role: '',
                total: 0,
                common:{
                    type: '',
                    addResourceTab: false,
                    titleTips: '',
                    isDisabled: false,
                    opeBtn:'1',
                    operatorTips: '',
                    resOperate: false,
                    editData:{},
                    resDetail:false,
                    editYARN:false
                },
                resUnit: resUnit,
                idDelete: true,
                resourceCon:{
                    name: '',
                    url: '',
                    capacity: '',
                    tenantList: [],
                    fileNum: '',
                    spaceName: '',
                    databaseName: ''
                },
                unit: 2,
                newResRules: {
                    url: [
                        { required: true, validator: validateUrl, trigger: 'blur' },
                        { min: 4, max: 12, message: '长度在 4 到 12 个字符', trigger: 'blur' }
                    ],
                    capacity: [
                        { required: true, validator: validateCapacity, trigger: 'blur' },
                        // { type:'number', min: 0, required: true, message: '请输入配额(格式为数字)', trigger: 'blur' },
                    ],
                    fileNum: [
                        { required: true, validator: validateFileNum, trigger: 'blur' },
                        // { type:'number', min: 0, required: true, message: '请输入文件数上限(格式为数字)', trigger: 'blur' },
                    ],
                    spaceName: [
                        { required: true, validator: validateUrl, trigger: 'blur' },
                        { min: 4, max: 12, message: '长度在 4 到 12 个字符', trigger: 'blur' }
                    ],
                    databaseName: [
                        { required: true, validator: validateUrl, trigger: 'blur' },
                        { min: 4, max: 12, message: '长度在 4 到 12 个字符', trigger: 'blur' }
                    ],
                    topicName: [
                        { required: true, validator: validateUrl, trigger: 'blur' },
                        { min: 4, max: 32, message: '长度在 4 到 32 个字符', trigger: 'blur' }
                    ],
                    partitionNum: [
                        { type:'number', min: 0, required: true, message: '请输入分区数(格式为数字)', trigger: 'blur' },
                    ],
                    replication: [
                        { type:'number', min: 0, required: true, message: '请输入副本数(格式为数字)', trigger: 'blur' },
                    ]
                },
                tenantList: [],
                pageSize: 10,
                btnDisabled: false,
                path: this.$route.path.toLocaleUpperCase(),
                loading: false,
                resourcePublic:[],
                // 容量配额校验（需要单位换算）
                savedCapacity: { value: 0, unit: 2},
                // 最大文件数校验
                savedFileNum: 0, // 当前资源已分配的文件数
                unUsedFileNum: 0, // 未分配的文件数
                remainFileTips:'',
                MaxReplicationNum: '最大输入副本数不能超过 0',
            }
        },
        computed: {
            ...mapState(["loginerRole"]),
        },
        watch:{
            diaData:{
                handler(val,oldval){
                    this.common = this.diaData;
                    this.resourceCon = JSON.parse(JSON.stringify(this.diaData.editData));
                    this.resourceCon.unit?this.unit = this.resourceCon.unit:'';
                    
                    // 记录 当前资源已分配的文件数
                    this.savedFileNum = this.resourceCon.fileNum
                    // 记录 当前资源已分配容量
                    this.savedCapacity.value = this.resourceCon.capacity
                    this.savedCapacity.unit = this.resourceCon.unit

                    if( this.common.addResourceTab && /HDFS/.test(this.path) ){ 
                        this.getRemain();
                        this.getFileRemain();
                    }
                    if(this.common.addResourceTab&&/KAFKA/.test(this.path)){
                        managerApi.getReplicationNum().then(res => {
                            this.MaxReplicationNum = '最大输入副本数不能超过 ' + res.data;
                        })
                    }
                    if(this.common.resOperate&&this.common.opeBtn==1){ 
                        this.getUser();
                        this.getTenant();
                    }
                    if(this.common.editYARN&&/YARN/.test(this.path)){
                        this.btnDisabled = true;
                        managerApi.syncYARN({resourceId: this.resourceCon.resourceId,level:this.resourceCon.level}).then(res => {
                            // 同步资源后请求列表
                            this.btnDisabled = false;
                            managerApi.queueList({resourceId: this.resourceCon.resourceId}).then(res=>{
                                this.resourcePublic = res.pageList
                                this.total = 0;
                                res.pageList.map(item => {
                                    this.total += (item.ratio-0);
                                })
                            })
                        }).catch(err => {
                            this.btnDisabled = false;
                        })
                    }
                },
                deep:true
            },
        },
        mounted(){
            this.addResourceTab = this.diaData.addResourceTab;
            if(this.loginerRole == MANAGER_ROLE_CODE){ //管理员
                this.role = '1';
            } else if(this.loginerRole == TENANT_ROLE_CODE) { //租户
                this.role = '2';
            } else {
                this.role = '3';
            }
        },
        methods:{
            changCount(type,val,index){
                if(type==0&&val>0){ //减
                    this.resourcePublic[index].ratio--;
                }else if(type==1&&val<100){
                    this.resourcePublic[index].ratio++;
                }
                this.total = 0;
                this.resourcePublic.map(item => {
                    this.total += (item.ratio-0);
                })
            },
            yarnEdit(){
                let obj = {
                    level: this.resourceCon.level,
                    parentId: this.resourceCon.resourceId,
                    yarnInfoList: []
                }
                let total = 0;
                this.resourcePublic.map(item => {
                    let yarnInfo = {
                        ratio: item.ratio,
                        queueName: item.queueName
                    };
                    total += item.ratio;
                    obj.yarnInfoList.push(yarnInfo);
                })
                if(total != 100){
                    Message.error("队列占比之和需要等于100！");
                    return;
                }
                this.btnDisabled = true;
                managerApi.modifyYARN(obj).then( res => {
                    this.btnDisabled = false;
                    this.common.editYARN = false;
                    Message.success('编辑成功！');
                    this.$parent.getResourceList();
                }).catch( err => {
                    this.btnDisabled = false;
                })
            },
            // 提交（操作）
            submitTenant(){
                let that = this;
                if(this.common.opeBtn == '1'){ //分配租户
                    let obj = {
                        resourceId: this.common.editData.resourceId,
                        
                        type: 1   // 管理员只有公共资源才能分配
                    }
                    // 租户是否选择
                    if(this.role == 1){
                        obj.tenantList = this.resourceCon.tenantList;
                        if(obj.tenantList.length == 0 && localStorage.selectLength == 0){
                            Message.error('请选择要分配的租户');
                            return;
                        }
                    }else{
                        obj.userList = this.resourceCon.userList
                        if(obj.userList.length == 0 && localStorage.selectLength == 0){
                            Message.error('请选择要分配的用户');
                            return;
                        }
                    }
                    
                    // 分配接口
                    this.btnDisabled = true;
                    if(/HDFS/.test(this.path)){
                        managerApi.distributeHDFS(obj).then( res =>{
                            that.successCB(2,'分配')
                        }).catch( err =>{
                            that.btnDisabled = false
                        })
                    }
                    if(/HBASE/.test(this.path)){
                        managerApi.distributeHBASE(obj).then( res =>{
                            that.successCB(2,'分配')
                        }).catch( err =>{
                            that.btnDisabled = false
                        })
                    }
                    if(/HIVE/.test(this.path)){
                        managerApi.distributeHIVE(obj).then( res =>{
                            that.successCB(2,'分配')
                        }).catch( err =>{
                            that.btnDisabled = false
                        })
                    }
                    if(/KAFKA/.test(this.path)){
                        managerApi.distributeKafka(obj).then( res =>{
                            that.successCB(2,'分配')
                        }).catch( err =>{
                            that.btnDisabled = false
                        })
                    }
                } else if(this.common.opeBtn == '3'){ //删除操作
                    let obj = {
                        keepData: this.idDelete?1:0,
                        resourceId: this.common.editData.resourceId
                    }
                    // 删除接口
                    this.btnDisabled = true;
                    if(/HDFS/.test(this.path)){
                        obj.url = '"'+this.common.editData.url+'"';
                        managerApi.delResHDFS(obj).then( res =>{
                            that.successCB(2,'删除',1)
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                    if(/HBASE/.test(this.path)){
                        obj.resourceName = this.common.editData.spaceName;
                        managerApi.delHBASERes(obj).then( res =>{
                            that.successCB(2,'删除',1)
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                    if(/HIVE/.test(this.path)){
                        obj.resourceName = this.common.editData.spaceName;
                        managerApi.delHIVERes(obj).then( res =>{
                            that.successCB(2,'删除',1)
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                    if(/YARN/.test(this.path)){
                        managerApi.delYARNRes({resourceId:this.common.editData.resourceId}).then( res =>{
                            that.successCB(2,'删除',1)
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                    if(/KAFKA/.test(this.path)){
                        managerApi.delKafka({resourceId:this.common.editData.resourceId}).then( res =>{
                            that.successCB(2,'删除',1)
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                }
            },
            // 资源操作 提交
            submitResourceCon(formName) {
                let that = this;
                // 表单校验
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let data = JSON.parse(JSON.stringify(that.resourceCon));
                        let obj = {};
                        this.common.isPublic == '1' ? obj.type = 1 : obj.type = 2;  //资源类型,1公共2租户3私有4共享
                        if(that.common.type=='HDFS'){ // HDFS 资源操作
                            obj.unit = that.unit;
                            obj.capacity = data.capacity;
                            obj.fileNum = data.fileNum;
                            that.common.isPublic == '1' ? obj.tenantList = data.tenantList : '';
                            that.btnDisabled = true;
                            if(that.common.isDisabled){ //编辑
                                obj.resourceId = data.resourceId;
                                managerApi.modifyHDFS(obj).then(res=>{
                                    that.successCB(1,'编辑')
                                }).catch(res => {
                                    that.btnDisabled = false;
                                })
                            } else { //新建
                                obj.url = '/public/' + that.resourceCon.url; // 完整的url路径
                                obj.tenantList = data.tenantList;
                                obj.parentId = 0; //新建的时候这个是父级Id(0)；
                                managerApi.postResHdfs(obj).then(res=>{
                                    that.successCB(1,'资源创建')
                                }).catch(res => {
                                    that.btnDisabled = false;
                                })
                            }
                        } else if(that.common.type=='HBASE'){
                            obj.cate = 1; //创建库
                            obj.spaceName = data.spaceName;
                            obj.tenantList = data.tenantList;
                            that.btnDisabled = true;
                            managerApi.postResHBASE(obj).then(res=>{
                                that.successCB(1,'资源创建')
                            }).catch(res => {
                                that.btnDisabled = false;
                            })
                        } else if(that.common.type=='HIVE'){
                            obj.type = 1;
                            obj.databaseName = data.databaseName;
                            that.btnDisabled = true;
                            managerApi.postResHIVE(obj).then(res=>{
                                that.successCB(1,'资源创建')
                            }).catch(res => {
                                that.btnDisabled = false;
                            })
                        } else if(that.common.type=='YARN'){
                            if(that.common.isDisabled){ //编辑
                                managerApi.modifyHDFS(data).then(res=>{
                                    that.successCB(1,'资源编辑')
                                }).catch(res => {
                                    that.btnDisabled = false;
                                })
                            } else { //新建
                                data.url = '/public/' + that.resourceCon.url;
                                managerApi.postResHdfs(data).then(res=>{
                                    that.successCB(1,'资源创建')
                                }).catch(res => {
                                    that.btnDisabled = false;
                                })
                            }
                        } else if(that.common.type=='KAFKA'){
                            obj.topicName = data.topicName;
                            obj.replication = data.replication;
                            obj.partitionNum = data.partitionNum;
                            managerApi.postResKafka(obj).then(res=>{
                                that.successCB(1,'资源创建')
                            }).catch(res => {
                                that.btnDisabled = false;
                            })
                        }
                    }
                });
            }
        }
    }
</script>

<style lang="scss" scoped>
.resourceForm{
    .el-dialog{
        width: 600px;
    }
    .el-input,.el-select{
        width: 480px;
    }
    .capUnit{
        .el-input{
            width: 360px;
        }
        .el-select{
            width: 115px;
        }
    }
    .el-dialog__body{
        padding-right: 20px;
    }
}
</style>
<style>
    .resourceDialog .el-dialog__body{
        padding-right: 20px;
    }
</style>